package com.hkbigdata.sybx.service.ipml;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.hkbigdata.sybx.bean.Video;
import com.hkbigdata.sybx.config.OssConfig;
import com.hkbigdata.sybx.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuanbo
 * @creat 2025-06-14-20:18
 * @see 2194550857@qq.com
 */
@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private OSS ossClient;

    @Autowired
    private OssConfig ossConfig;

    @Override
    public List<Video> listVideos() {
        List<Video> videos = new ArrayList<>();
        try {
            // 列举所有视频文件
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ossConfig.getBucketName());
            // 设置前缀，只获取视频文件
            listObjectsRequest.setPrefix("videos/");  // 假设视频都存储在videos目录下
            // 设置文件类型过滤
            listObjectsRequest.setDelimiter("/");

            ObjectListing listing = ossClient.listObjects(listObjectsRequest);

            // 处理每个视频文件
            for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                String fileName = objectSummary.getKey();
                // 只处理视频文件
                if (isVideoFile(fileName)) {
                    Video video = new Video();
                    video.setName(fileName);
                    // 从文件名中提取标题（可以根据实际需求修改）
                    video.setTitle(extractTitleFromFileName(fileName));
                    video.setDesc("视频描述");  // 可以从数据库或其他地方获取
                    video.setViews("0");
                    video.setPracticed("0");
                    video.setCreateTime(objectSummary.getLastModified());
                    videos.add(video);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("获取视频列表失败");
        }
        return videos;
    }

    private boolean isVideoFile(String fileName) {
        String[] videoExtensions = {".mp4", ".avi", ".mov", ".wmv", ".flv"};
        String lowerFileName = fileName.toLowerCase();
        for (String ext : videoExtensions) {
            if (lowerFileName.endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    private String extractTitleFromFileName(String fileName) {
        // 从文件名中提取标题，去掉扩展名和路径
        String name = fileName.substring(fileName.lastIndexOf("/") + 1);
        return name.substring(0, name.lastIndexOf("."));
    }
}
